package cn.damong.utils.common;

import java.io.IOException;
import java.net.URL;
import java.util.Map;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import net.sf.json.JSONObject;


/**
 * json工具类
 * 
 * @author CodingPanda
 * @2019年5月15日 下午11:20:42
 *
 */
public class JsonUtil {
	
	private JsonUtil(){}
	
	/**
     * Object 转换为 JSON字符串
     *
     * @param obj
     * @return
     */
    public static String obj2Json(Object obj) {
        try {
            return getInstance().writeValueAsString(obj);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * JSON字符串 转换为 Object
     *
     * @param json
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T json2Obj(String json, Class<T> clazz) {
        try {
            return getInstance().readValue(json, clazz);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * JSON字符串 转换为 Object
     *
     * @param json
     * @param typeReference
     * @param <T>
     * @return
     */
    public static <T> T json2Obj(URL json, TypeReference<T> typeReference) {
        try {
            return getInstance().readValue(json, typeReference);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * JSON字符串 转换为 Object
     *
     * @param json
     * @param typeReference
     * @param <T>
     * @return
     */
    public static <T> T json2Obj(String json, TypeReference<T> typeReference) {
        try {
            return getInstance().readValue(json, typeReference);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
    
    /**
     * json string 转换为 map 对象
     * @param jsonObj
     * @return
     */
	@SuppressWarnings("unchecked")
	public static Map<Object, Object> jsonToMap(Object jsonObj) {
        JSONObject jsonObject = JSONObject.fromObject(jsonObj);
		Map<Object, Object> map = jsonObject;
        return map;
    }

    private static ObjectMapper getInstance() {
        return SingletonHolder.instance;
    }

    private static final class SingletonHolder {
        private static final ObjectMapper instance = new ObjectMapper();

        static {
            // 忽略JSON字符串中存在而Java对象实际没有的属性
            instance.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        }
    }

}
